import type { ParallelTaskExecuteContext } from '../handler'
import type { PrivateCustomEventName } from '../types'
import type { TranscodeWorkerReplyWorkerMessage, TranscodeWorkerSendWorkerMessage } from '../worker'

import { ParallelHandler } from '../handler'
import { createEventBus } from '../utils'

// eslint-disable-next-line ts/ban-ts-comment
// @ts-ignore
import TranscodeWorker from '../worker/transcode-worker?worker&inline'

const $bus = createEventBus<PrivateCustomEventName>()

class ResponseTranscode extends ParallelHandler<string, Array<number>> {
  private transcodeWorkerInstance: Worker | null = null

  onActive(): void {
    this.transcodeWorkerInstance = new TranscodeWorker()

    this.transcodeWorkerInstance?.addEventListener('message', (event: MessageEvent<TranscodeWorkerReplyWorkerMessage>): void => {
      const { type, data } = event.data

      if (type === 'success') {
        const { audioData } = data

        this.forwardToHandler(audioData)
      }
      this.taskCompletedCallback(data.uuid)
    })
  }

  public execute(context: ParallelTaskExecuteContext<string, Array<number>>): void {
    if (context.isLastExecute) {
      this.taskCompletedCallback(context.taskItem.uuid)
      return
    }

    this.transcodeWorkerInstance?.postMessage({
      type: 'send',
      data: context.taskItem,
    } as TranscodeWorkerSendWorkerMessage)
  }

  protected onFinish(): void {
    $bus.emit('_responseTranscodeFinish')
    if (this.transcodeWorkerInstance) {
      this.transcodeWorkerInstance.terminate()
    }
  }
}

export default ResponseTranscode
